﻿using BLL;
using Models;
using Inspinia_MVC5.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Inspinia_MVC5.Code
{
    public class ResultHelper
    {
        //原始自带函数
        #region
        public static string DateTimeConvertString(DateTime? dt)
        {
            if (!dt.HasValue)
            {
                return "";
            }
            return Convert.ToDateTime(dt.ToString()).ToShortDateString();
        }

        public static string GetUserIP()
        {
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
            }
            return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        public static string InputText(string inputString)
        {
            if ((inputString != null) && (inputString != string.Empty))
            {
                inputString = inputString.Trim();
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("&", "&amp");
                inputString = inputString.Replace("'", "''");
                inputString = inputString.Replace("<", "&lt");
                inputString = inputString.Replace(">", "&gt");
                inputString = inputString.Replace("chr(60)", "&lt");
                inputString = inputString.Replace("chr(37)", "&gt");
                inputString = inputString.Replace("\"", "&quot");
                inputString = inputString.Replace(";", ";");
                return inputString;
            }
            return "";
        }

        public static string OutputText(string outputString)
        {
            if ((outputString != null) && (outputString != string.Empty))
            {
                outputString = outputString.Trim();
                outputString = outputString.Replace("&amp", "&");
                outputString = outputString.Replace("''", "'");
                outputString = outputString.Replace("&lt", "<");
                outputString = outputString.Replace("&gt", ">");
                outputString = outputString.Replace("&lt", "chr(60)");
                outputString = outputString.Replace("&gt", "chr(37)");
                outputString = outputString.Replace("&quot", "\"");
                outputString = outputString.Replace(";", ";");
                outputString = outputString.Replace("\n", "<br>");
                return outputString;
            }
            return "";
        }

        public static DateTime? StringConvertDatetime(string str)
        {
            if (str == null)
            {
                return null;
            }
            try
            {
                return new DateTime?(Convert.ToDateTime(str));
            }
            catch
            {
                return null;
            }
        }

        public static bool ValidateSQL(string sql, ref string msg)
        {
            if (sql.ToLower().IndexOf("delete") > 0)
            {
                msg = "查询参数中含有非法语句DELETE";
                return false;
            }
            if (sql.ToLower().IndexOf("update") > 0)
            {
                msg = "查询参数中含有非法语句UPDATE";
                return false;
            }
            if (sql.ToLower().IndexOf("insert") > 0)
            {
                msg = "查询参数中含有非法语句INSERT";
                return false;
            }
            return true;
        }

        public static string NewId
        {
            get
            {
                string str = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                string str2 = Guid.NewGuid().ToString().Replace("-", "");
                return (str + str2.Substring(0, 10));
            }
        }

        public static string NewTimeId
        {
            get
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
            }
        }

        public static DateTime NowTime
        {
            get
            {
                return DateTime.Now;
            }
        }
        #endregion

        public static string e2c(string e)
        {
            switch (e)
            {
                case "Admin":
                    return "管理员";
                case "Manager":
                    return "高级技术人员";
                case "Worker":
                default:
                    return "基本工作人员";
            }
        }
        public static float[] s2f(string e, int num)
        {
            float[] data = new float[200];
            string[] arreys = e.Split(' ');
            for (int i = 0; i < 200; i++)
            {
                data[i] = float.Parse(arreys[i]) / num;
            }
            return data;
        }
        //执行sql语句
        public static DataTable sqlQueryForDataTatable(Database db, string sql)
        {

            SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = db.Connection.ConnectionString;
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            return table;
        }
        //获取实时曲线的初始化数据
        public static DataTable getInitializationLine(string wellId, string tablename, string num)
        {
            using (var Db = new DBContainer())
            {
                string sql = "SELECT TOP " + num + " * FROM " + tablename + " WHERE Well_ID = '" + wellId + "' order by Time desc ";
                DataTable q = sqlQueryForDataTatable(Db.Database, sql).Copy();
                return q;
            }
        }
        //获取实时曲线的实时数据
        public static DataTable getNewLineData(string wellId, string tablename)
        {
            using (var Db = new DBContainer())
            {
                string sql = "SELECT * FROM RealTimeData WHERE Well_ID = '" + wellId + "'";
                DataTable q = sqlQueryForDataTatable(Db.Database, sql).Copy();
                return q;
            }
        }
        //获取历史曲线的数据
        public static DataTable getHistoryLine(string wellId, string tablename, string starttime, string endtime)
        {
            using (var Db = new DBContainer())
            {
                string sql = "SELECT * FROM " + tablename + " WHERE Well_ID = '" + wellId + "' and (Time between '" + starttime + "' and '" + endtime + "') order by Time desc ";
                DataTable q = sqlQueryForDataTatable(Db.Database, sql).Copy();
                return q;
            }
        }
        //获取一口井的num个最近示功图数据
        public static List<IndicatorModel> getIndicatorsByNum(string wellid,string wellname, int num)
        {
            R_SIGN_INDDService R_SIGN_INDDService = new R_SIGN_INDDService();
            R_SIGN_IMPORTANTService R_SIGN_IMPORTANTService = new R_SIGN_IMPORTANTService();
            R_SIGN_MainService R_SIGN_MainService = new R_SIGN_MainService();
            var indds = R_SIGN_INDDService.FindAll(c => c.Well_ID == wellid).OrderByDescending(c => c.Time).Take(num).ToList();
            var importants = R_SIGN_IMPORTANTService.FindAll(c => c.Well_ID == wellid).OrderByDescending(c => c.Time).Take(num).ToList();
            var mains = R_SIGN_MainService.FindAll(c => c.Well_ID == wellid).OrderByDescending(c => c.Time).Take(num).ToList();
            List<IndicatorModel> InddListModel = new List<IndicatorModel>();
            R_SIGN_IMPORTANT important = new R_SIGN_IMPORTANT();
            R_SIGN_Main main = new R_SIGN_Main();
            R_SIGN_INDD indd = new R_SIGN_INDD();
            for (int i = 0; i < num; i++)
            {
                IndicatorModel indicator = new IndicatorModel();
                if (indds.Count() >= i + 1)
                { indd = indds[i]; }
                else { continue; }
                if (importants.Count() >= i + 1)
                { important = importants[i]; }
                else { continue; }
                if (mains.Count() >= i + 1)
                { main = mains[i]; }
                else { continue; }
                indicator.Well_ID = indd.Well_ID;
                indicator.Well_Name = wellname;
                //indicator.Datetime = indd.Time.ToString("yyyy-MM-dd HH:mm:ss");
                indicator.Datetime = indd.Time.ToString("MM/dd/yyyy HH:mm:ss");
                indicator.Indd_Data_Disp = s2f(indd.MW4097 + indd.MW4107 + indd.MW4117 + indd.MW4127 + indd.MW4137 + indd.MW4147 + indd.MW4157 + indd.MW4167 + indd.MW4177 + indd.MW4187 + indd.MW4197 + indd.MW4207 + indd.MW4217 + indd.MW4227 + indd.MW4237 + indd.MW4247 + indd.MW4257 + indd.MW4267 + indd.MW4277 + indd.MW4287, 1000);
                indicator.Indd_Data_Load = s2f(indd.MW4297 + indd.MW4307 + indd.MW4317 + indd.MW4327 + indd.MW4337 + indd.MW4347 + indd.MW4357 + indd.MW4367 + indd.MW4377 + indd.MW4387 + indd.MW4397 + indd.MW4407 + indd.MW4417 + indd.MW4427 + indd.MW4437 + indd.MW4447 + indd.MW4457 + indd.MW4467 + indd.MW4477 + indd.MW4487, 100);
                indicator.ID = i;
                indicator.Stroke = Convert.ToSingle(indd.MW4091) / 1000;
                indicator.Stroketimes = Convert.ToSingle(indd.MW4092) / 100;
                indicator.maxload = Convert.ToSingle(indd.MW4095) / 100;
                indicator.minload = Convert.ToSingle(indd.MW4096) / 100;
                indicator.Manif_Press = (Convert.IsDBNull(important.MW1007)) ? 0 : Convert.ToSingle(important.MW1007);
                indicator.Manif_Temp = (Convert.IsDBNull(important.MW1008)) ? 0 : Convert.ToSingle(important.MW1008);
                indicator.O_Press = (Convert.IsDBNull(important.MW1009)) ? 0 : Convert.ToSingle(important.MW1009);
                indicator.O_Temp = (Convert.IsDBNull(important.MW1010)) ? 0 : Convert.ToSingle(important.MW1010);
                indicator.Cas_Press = (Convert.IsDBNull(important.MW1011)) ? 0 : Convert.ToSingle(important.MW1011);
                indicator.Actpow = (Convert.IsDBNull(important.MW1041)) ? 0 : Convert.ToSingle(important.MW1041);
                indicator.Bal_Rate = (Convert.IsDBNull(important.Calc001)) ? 0 : Convert.ToSingle(important.Calc001);
                indicator.Sys_Eff = (Convert.IsDBNull(important.Calc002)) ? 0 : Convert.ToSingle(important.Calc002);
                indicator.Pow_Factor = (Convert.IsDBNull(main.MW1044)) ? 0 : Convert.ToSingle(main.MW1044);
                InddListModel.Add(indicator);
            }
            return InddListModel;
        }
        //获取一口井的示功图数据
        public static List<IndicatorModel> getIndicatorsByTime(string wellid, DateTime starttime, DateTime endtime)
        {
            R_SIGN_INDDService R_SIGN_INDDService = new R_SIGN_INDDService();
            R_SIGN_IMPORTANTService R_SIGN_IMPORTANTService = new R_SIGN_IMPORTANTService();
            R_SIGN_MainService R_SIGN_MainService = new R_SIGN_MainService();
            R_SIGN_AssociatedService rsa = new R_SIGN_AssociatedService();
            var indds = R_SIGN_INDDService.FindAll(c => c.Well_ID == wellid && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            var importants = R_SIGN_IMPORTANTService.FindAll(c => c.Well_ID == wellid && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            var mains = R_SIGN_MainService.FindAll(c => c.Well_ID == wellid && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            var timersaups = rsa.FindAll(c => c.Well_ID == wellid && c.MW0033 == "1 " && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            var timersadowns = rsa.FindAll(c => c.Well_ID == wellid && c.MW0033 == "2 " && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            List<IndicatorModel> InddListModel = new List<IndicatorModel>();
            R_SIGN_IMPORTANT important = new R_SIGN_IMPORTANT();
            R_SIGN_Main main = new R_SIGN_Main();
            R_SIGN_INDD indd = new R_SIGN_INDD();
            R_SIGN_Associated timersaup = new R_SIGN_Associated();
            R_SIGN_Associated timersadown = new R_SIGN_Associated();
            for (int i = 0; i < indds.Count(); i++)
            {
                IndicatorModel indicator = new IndicatorModel();
                if (indds.Count() >= i + 1)
                { indd = indds[i]; }
                else { continue; }
                if (importants.Count() >= i + 1)
                { important = importants[i]; }
                else { continue; }
                if (mains.Count() >= i + 1)
                { main = mains[i]; }
                else { continue; }
                timersaup = timersaups.FindAll(c => c.Time < indd.Time).OrderByDescending(c => c.Time).ToList().First();
                timersadown = timersadowns.FindAll(c => c.Time < indd.Time).OrderByDescending(c => c.Time).ToList().First();
                indicator.Well_ID = indd.Well_ID;
                indicator.Datetime = indd.Time.ToString("yyyy-MM-dd HH:mm:ss");
                indicator.Indd_Data_Disp = s2f(indd.MW4097 + indd.MW4107 + indd.MW4117 + indd.MW4127 + indd.MW4137 + indd.MW4147 + indd.MW4157 + indd.MW4167 + indd.MW4177 + indd.MW4187 + indd.MW4197 + indd.MW4207 + indd.MW4217 + indd.MW4227 + indd.MW4237 + indd.MW4247 + indd.MW4257 + indd.MW4267 + indd.MW4277 + indd.MW4287, 1000);
                indicator.Indd_Data_Load = s2f(indd.MW4297 + indd.MW4307 + indd.MW4317 + indd.MW4327 + indd.MW4337 + indd.MW4347 + indd.MW4357 + indd.MW4367 + indd.MW4377 + indd.MW4387 + indd.MW4397 + indd.MW4407 + indd.MW4417 + indd.MW4427 + indd.MW4437 + indd.MW4447 + indd.MW4457 + indd.MW4467 + indd.MW4477 + indd.MW4487, 100);
                indicator.ID = i;
                indicator.Stroke = Convert.ToSingle(indd.MW4091) / 1000;
                indicator.Stroketimes = Convert.ToSingle(indd.MW4092) / 100;
                indicator.maxload = Convert.ToSingle(indd.MW4095) / 100;
                indicator.minload = Convert.ToSingle(indd.MW4096) / 100;
                indicator.Manif_Press = (Convert.IsDBNull(important.MW1007)) ? 0 : Convert.ToSingle(important.MW1007);
                indicator.Manif_Temp = (Convert.IsDBNull(important.MW1008)) ? 0 : Convert.ToSingle(important.MW1008);
                indicator.O_Press = (Convert.IsDBNull(important.MW1009)) ? 0 : Convert.ToSingle(important.MW1009);
                indicator.O_Temp = (Convert.IsDBNull(important.MW1010)) ? 0 : Convert.ToSingle(important.MW1010);
                indicator.Cas_Press = (Convert.IsDBNull(important.MW1011)) ? 0 : Convert.ToSingle(important.MW1011);
                indicator.Actpow = (Convert.IsDBNull(important.MW1041)) ? 0 : Convert.ToSingle(important.MW1041);
                indicator.Bal_Rate = (Convert.IsDBNull(important.Calc001)) ? 0 : Convert.ToSingle(important.Calc001);
                indicator.Sys_Eff = (Convert.IsDBNull(important.Calc002)) ? 0 : Convert.ToSingle(important.Calc002);
                indicator.Pow_Factor = (Convert.IsDBNull(main.MW1044)) ? 0 : Convert.ToSingle(main.MW1044);
                indicator.UpCurrent = (Convert.IsDBNull(timersaup.MW0011)) ? 0 : Convert.ToSingle(timersaup.MW0011)/10;
                indicator.DownCurrent = (Convert.IsDBNull(timersadown.MW0011)) ? 0 : Convert.ToSingle(timersadown.MW0011)/10;
                InddListModel.Add(indicator);
            }
            return InddListModel;
        }
        //获取一口井的电流功图数据
        public static List<SimpleIndicatorModel> getDianLiuIndicatorsByTime(string wellid, DateTime starttime, DateTime endtime)
        {
            R_SIGN_ELECDService R_SIGN_ELECDService = new R_SIGN_ELECDService();
            var indds = R_SIGN_ELECDService.FindAll(c => c.Well_ID == wellid && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            List<SimpleIndicatorModel> SimpleIndicatorModel = new List<SimpleIndicatorModel>();
            R_SIGN_ELECD indd = new R_SIGN_ELECD();
            for (int i = 0; i < indds.Count(); i++)
            {
                SimpleIndicatorModel indicator = new SimpleIndicatorModel();
                if (indds.Count() >= i + 1)
                { indd = indds[i]; }
                else { continue; }
                indicator.Well_ID = indd.Well_ID;
                indicator.Datetime = indd.Time.ToString("yyyy-MM-dd HH:mm:ss");
                indicator.Indd_Data_Disp = s2f(indd.MW4097  + indd.MW4147 + indd.MW4197 + indd.MW4247, 1000);
                indicator.Indd_Data_Load = s2f(indd.MW4497 + indd.MW4547 + indd.MW4597 + indd.MW4647, 100);
                indicator.ID = i;
                SimpleIndicatorModel.Add(indicator);
            }
            return SimpleIndicatorModel;
        }
        //获取一口井的有功功率功图数据
        public static List<SimpleIndicatorModel> getYouGongIndicatorsByTime(string wellid, DateTime starttime, DateTime endtime)
        {
            R_SIGN_ELECDService R_SIGN_ELECDService = new R_SIGN_ELECDService();
            var indds = R_SIGN_ELECDService.FindAll(c => c.Well_ID == wellid && c.Time >= starttime && c.Time <= endtime).OrderByDescending(c => c.Time).ToList();
            List<SimpleIndicatorModel> SimpleIndicatorModel = new List<SimpleIndicatorModel>();
            R_SIGN_ELECD indd = new R_SIGN_ELECD();
            for (int i = 0; i < indds.Count(); i++)
            {
                SimpleIndicatorModel indicator = new SimpleIndicatorModel();
                if (indds.Count() >= i + 1)
                { indd = indds[i]; }
                else { continue; }
                indicator.Well_ID = indd.Well_ID;
                indicator.Datetime = indd.Time.ToString("yyyy-MM-dd HH:mm:ss");
                indicator.Indd_Data_Disp = s2f(indd.MW4097 + indd.MW4147 + indd.MW4197 + indd.MW4247, 1000);
                indicator.Indd_Data_Load = s2f(indd.MW4697 + indd.MW4747 + indd.MW4797 + indd.MW4847, 100);
                indicator.ID = i;
                SimpleIndicatorModel.Add(indicator);
            }
            return SimpleIndicatorModel;
        }
        //获取一口井的num个最近报警记录
        public static List<WarnLogModel> getWarnsByNum(string wellid, int num)
        {
            R_INFO_Error_RecordeService R_INFO_Error_RecordeService = new R_INFO_Error_RecordeService();
            R_INFO_StructureService R_INFO_StructureService = new R_INFO_StructureService();
            var riers = R_INFO_Error_RecordeService.FindAll(c => c.WELL_ID == wellid).OrderByDescending(c => c.ActionTime).Take(num).ToList();
            List<WarnLogModel> WarnLogListModel = new List<WarnLogModel>();
            R_INFO_Error_Recorde rier = new R_INFO_Error_Recorde();
            for (int i = 0; i < num; i++)
            {
                WarnLogModel warnlog = new WarnLogModel();
                if (riers.Count() >= i + 1)
                { rier = riers[i]; }
                else { continue; }
                warnlog.RecordeID = rier.ID;
                warnlog.WELL_ID = rier.WELL_ID;
                warnlog.ActionTime = rier.ActionTime.ToString("yyyy-MM-dd HH:mm:ss");
                warnlog.IDCode = R_INFO_StructureService.Find(c => c.IDCode == rier.IDCode).Describe;
                if (rier.ErrorEndTime.HasValue)
                {
                    warnlog.ErrorEndTime = rier.ErrorEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (rier.isCheck == null || rier.isCheck.Contains("1"))
                {
                    warnlog.isCheck = "Pending";
                }
                else if (rier.isCheck.Contains("2"))
                {
                    warnlog.isCheck = "Ignored";
                }
                WarnLogListModel.Add(warnlog);
            }
            return WarnLogListModel;
        }
        //获取一口井的报警记录
        public static List<WarnLogModel> getWarnsByWellid(string wellid)
        {
            R_INFO_Error_RecordeService R_INFO_Error_RecordeService = new R_INFO_Error_RecordeService();
            R_INFO_StructureService R_INFO_StructureService = new R_INFO_StructureService();
            var riers = R_INFO_Error_RecordeService.FindAll(c => c.WELL_ID == wellid).OrderByDescending(c => c.ActionTime).ToList();
            List<WarnLogModel> WarnLogListModel = new List<WarnLogModel>();
            foreach (var rier in riers)
            {
                WarnLogModel warnlog = new WarnLogModel();
                warnlog.RecordeID = rier.ID;
                warnlog.WELL_ID = rier.WELL_ID;
                warnlog.ActionTime = rier.ActionTime.ToString("yyyy-MM-dd HH:mm:ss");
                warnlog.IDCode = R_INFO_StructureService.Find(c => c.IDCode == rier.IDCode).Describe;
                if (rier.ErrorEndTime.HasValue)
                {
                    warnlog.ErrorEndTime = rier.ErrorEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (rier.isCheck == null || rier.isCheck.Contains("1"))
                {
                    warnlog.isCheck = "Pending";
                }
                else if (rier.isCheck.Contains("2"))
                {
                    warnlog.isCheck = "Ignored";
                }
                WarnLogListModel.Add(warnlog);
            }
            return WarnLogListModel;
        }
        //获取一口井的操作记录
        public static List<WarnLogModel> getOperationsByWellid(string wellid)
        {
            R_ADJU_RecordeService R_ADJU_RecordeService = new R_ADJU_RecordeService();
            R_CTRL_RecordeService R_CTRL_RecordeService = new R_CTRL_RecordeService();
            R_ADJU_StructureService R_ADJU_StructureService = new R_ADJU_StructureService();
            R_CTRL_StructureService R_CTRL_StructureService = new R_CTRL_StructureService();
            var rarss = R_ADJU_RecordeService.FindAll(c => c.WELL_ID == wellid).OrderByDescending(c => c.ActionTime).ToList();
            var rcrss = R_CTRL_RecordeService.FindAll(c => c.WELL_ID == wellid).OrderByDescending(c => c.ActionTime).ToList();
            List<WarnLogModel> WarnLogListModel = new List<WarnLogModel>();
            foreach (var rars in rarss)
            {
                WarnLogModel warnlog = new WarnLogModel();
                warnlog.OperatorID = rars.OperatorID;
                warnlog.WELL_ID = rars.WELL_ID;
                warnlog.ActionTime = rars.ActionTime.ToString("yyyy-MM-dd HH:mm:ss");
                warnlog.Status_Before = rars.Status_Before;
                warnlog.Status_Now = rars.Status_Now;
                warnlog.IDCode = R_ADJU_StructureService.Find(c => c.IDCode == rars.IDCode).Describe;
                warnlog.isCheck = "遥控";
                WarnLogListModel.Add(warnlog);
            }
            foreach (var rcrs in rcrss)
            {
                WarnLogModel warnlog = new WarnLogModel();
                warnlog.OperatorID = rcrs.OperatorID;
                warnlog.WELL_ID = rcrs.WELL_ID;
                warnlog.ActionTime = rcrs.ActionTime.ToString("yyyy-MM-dd HH:mm:ss");
                warnlog.Status_Before = rcrs.Status_Before;
                warnlog.Status_Now = rcrs.Status_Now;
                warnlog.IDCode = R_CTRL_StructureService.Find(c => c.IDCode == rcrs.IDCode).Describe;
                warnlog.isCheck = "遥调";
                WarnLogListModel.Add(warnlog);
            }
            return WarnLogListModel;
        }
        //获取一口井的全部数据记录
        public static List<DataModel> getDataByWellid(string wellid)
        {
            R_INFO_StructureService R_INFO_StructureService = new R_INFO_StructureService();
            R_ADJU_StructureService R_ADJU_StructureService = new R_ADJU_StructureService();
            R_SIGN_StructureService R_SIGN_StructureService = new R_SIGN_StructureService();
            R_INFO_DataService R_INFO_DataService = new R_INFO_DataService();
            Well2SensorService Well2SensorService = new Well2SensorService();
            DataTable rids = new DataTable();
            DataTable rsad = new DataTable();
            DataTable raad = new DataTable();
            using (var Db = new DBContainer())
            {
                string sql1 = "SELECT TOP 1 * FROM R_INFO_Data WHERE Well_ID = '" + wellid + "' order by Time desc ";
                rids = sqlQueryForDataTatable(Db.Database, sql1).Copy();
                string sql2 = "SELECT TOP 1 * FROM R_SIGN_ALLDATA WHERE Well_ID = '" + wellid + "' order by Time desc ";
                rsad = sqlQueryForDataTatable(Db.Database, sql2).Copy();
                string sql3 = "SELECT TOP 1 * FROM R_ADJU_ALLDATA WHERE Well_ID = '" + wellid + "' order by Time desc ";
                raad = sqlQueryForDataTatable(Db.Database, sql3).Copy();
            }
            var risss = R_INFO_StructureService.All().ToList();
            var rasss = R_ADJU_StructureService.All().ToList();
            var rssss = R_SIGN_StructureService.All().ToList();
            List<DataModel> DataListModel = new List<DataModel>();
            if (rids.Rows.Count > 0)
            {
                for (int i = 0; i < rids.Columns.Count; i++)
                {
                    if (rids.Columns[i].ColumnName.Contains("ID") || rids.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    string IDCode = rids.Columns[i].ColumnName;
                    var riss = risss.Find(c => c.IDCode.Trim() == IDCode);
                    DataModel data = new DataModel();
                    data.WellId = wellid;
                    data.Identifier = IDCode;
                    data.Parameter = riss.Describe.Trim();
                    //data.Unit = riss.Unit == null ? "" : riss.Unit.Trim();
                    data.Range = riss.Range == null ? "暂无" : riss.Range.Trim();
                    data.Style = "遥信";
                    data.Datetime = rids.Rows[0][2].ToString();
                    data.Value = (Convert.ToDouble(rids.Rows[0][i].ToString()) * riss.Scaler).ToString() + (riss.Unit == null ? "" : riss.Unit.Trim());
                    DataListModel.Add(data);
                }
            }
            if (raad.Rows.Count > 0)
            {
                for (int i = 0; i < raad.Columns.Count; i++)
                {
                    if (raad.Columns[i].ColumnName.Contains("ID") || raad.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    string IDCode = raad.Columns[i].ColumnName;
                    var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                    DataModel data = new DataModel();
                    data.WellId = wellid;
                    data.Identifier = IDCode;
                    data.Parameter = rass.Describe.Trim();
                    //data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                    data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                    data.Style = "遥调";
                    data.Datetime = raad.Rows[0][1].ToString();
                    data.Value = (Convert.ToDouble(raad.Rows[0][i].ToString()) * rass.Scaler).ToString() + (rass.Unit == null ? "" : rass.Unit.Trim());
                    DataListModel.Add(data);
                }
            }
            if (rsad.Rows.Count > 0)
            {
                for (int i = 0; i < rsad.Columns.Count; i++)
                {
                    if (rsad.Columns[i].ColumnName.Contains("ID") || rsad.Columns[i].ColumnName.Contains("Time") || rsad.Rows[0][i].ToString().Split(' ').Length > 2)
                    {
                        continue;
                    }
                    string IDCode = rsad.Columns[i].ColumnName;
                    var rsss = rssss.Find(c => c.IDCode.Trim() == IDCode);
                    DataModel data = new DataModel();
                    data.WellId = wellid;
                    data.Identifier = IDCode;
                    data.Parameter = rsss.Describe.Trim();
                    //data.Unit = rsss.Unit == null ? "" : rsss.Unit.Trim();
                    data.Range = rsss.Range == null ? "暂无" : rsss.Range.Trim();
                    data.Style = "遥测";
                    data.Datetime = rsad.Rows[0][1].ToString();
                    data.Value = (Convert.ToDouble(rsad.Rows[0][i].ToString()) * rsss.Scaler).ToString() + (rsss.Unit == null ? "" : rsss.Unit.Trim());
                    DataListModel.Add(data);
                }
            }
            return DataListModel;
        }
        //获取全部数据的时间和值
        public static DataTable getTimeValue(string wellId, string tablename, string idcode)
        {
            using (var Db = new DBContainer())
            {
                string sql = "SELECT TOP 1 Time," + idcode + " FROM " + tablename + " WHERE Well_ID = '" + wellId + "' order by Time desc ";
                DataTable q = sqlQueryForDataTatable(Db.Database, sql).Copy();
                return q;
            }
        }
        public static List<ReportDataModel> getReportData(string wellstr, string datetime)
        {
            DateTime starttime = Convert.ToDateTime(datetime+" 00:00:00");
            DateTime endtime = Convert.ToDateTime(datetime+" 23:59:59");
            WellService WellService = new WellService();
            R_SIGN_IMPORTANTService R_SIGN_IMPORTANTService = new R_SIGN_IMPORTANTService();
            R_SIGN_NEWService R_SIGN_NEWService = new R_SIGN_NEWService();
            R_SIGN_MIVService R_SIGN_MIVService = new R_SIGN_MIVService();
            List<ReportDataModel> rdms = new List<ReportDataModel>();
            var wells = WellService.All();
            if(wellstr != "0")
            {

                wells = wells.Where(c => wellstr.Contains("-" + c.ID.ToString() + "-"));
            }
            foreach (var well in wells)
            {
                ReportDataModel rdm = new ReportDataModel();
                List<R_SIGN_IMPORTANT> rsis = R_SIGN_IMPORTANTService.FindAll(c => c.Well_ID == well.ID.ToString() && c.Time >= starttime && c.Time <= endtime).ToList();
                List<R_SIGN_NEW> rsns = R_SIGN_NEWService.FindAll(c => c.Well_ID == well.ID.ToString() && c.Time >= starttime && c.Time <= endtime).ToList();
                List<R_SIGN_MIV> rsms = R_SIGN_MIVService.FindAll(c => c.Well_ID == well.ID.ToString() && c.Time >= starttime && c.Time <= endtime).ToList();
                rdm.BlockId = well.BLOCK_ID.ToString();
                rdm.WellId = well.ID.ToString();
                //rdm.XingHao = well.Station.Split('_')[1];
                rdm.XingHao = "";
                rdm.CengWei = "";
                rdm.JingDuan = "";
                rdm.Time = "";
                if(rsns.Count == 0)
                {
                    rdm.ChongCheng = "";
                    rdm.ChongCi = "";
                }
                else
                {
                    rdm.ChongCheng = (rsns.Average(c => int.Parse(c.MW0006))/100).ToString("#0.00");
                    rdm.ChongCi = (rsns.Average(c => int.Parse(c.MW0007))/100).ToString("#0.00");
                }
                if (rsis.Count == 0)
                {
                    rdm.TaoYa = "";
                    rdm.HuiYa = "";
                    rdm.WenDu = "";
                }
                else
                {
                    rdm.TaoYa = rsis.Average(c => int.Parse(c.MW1011)).ToString();
                    rdm.HuiYa = rsis.Average(c => int.Parse(c.MW1007)).ToString();
                    rdm.WenDu = rsis.Average(c => int.Parse(c.MW1010)).ToString();
                }
                if (rsms.Count == 0)
                {
                    rdm.YouLiang = "";
                    rdm.ShuiLiang = "";
                    rdm.QiLiang = "";
                }
                else
                {
                    rdm.YouLiang = rsms.Average(c => int.Parse(c.MW1344)).ToString();
                    rdm.ShuiLiang = rsms.Average(c => int.Parse(c.MW1347)).ToString();
                    rdm.QiLiang = rsms.Average(c => int.Parse(c.MW1341)).ToString();
                }
                rdms.Add(rdm);
            }
            return rdms;
        }
    }
}